<template>
  <div class="go-check-publish">
    <head-top :head-title="$route.params.name" hidden='true' go-back="true" check-publish="提交"
              @checkPublish="submitCheck" v-show="$route.params.hid === '0'"></head-top>
    <head-top :head-title="$route.params.name" hidden='true' go-back="true" recheck-publish="重新提交"
              @reCheckPublish="reSubmitCheck" v-show="$route.params.hid !== '0'"></head-top>
    <div class="rent_main">
      <div class="vue-upload-img-multiple">
        <ul>
          <li class="line" v-show="image" v-for="(image,index) in img" :key="index">
            <div class="img_size">
              <div :style="'backgroundImage:url('+image+')'" class="picture" @click="previewImg(index)"></div>
              <span @click='deleteEveryImage(img, index)' class="remove">x</span>
            </div>
          </li>
          <li v-show="image && !isIOS" v-for="(image,index) in images.localId" :key="index">
            <div class="img_size">
              <div :style="'backgroundImage:url('+image+')'" class="picture" @click="preview(index)"></div>
              <span @click='delImage(index)' class="remove">x</span>
            </div>
          </li>
          <li v-show="image && isIOS" v-for="(image,index) in images.iosLocalId" :key="index">
            <div class="img_size">
              <div :style="'backgroundImage:url('+image+')'" class="picture" @click="preview(index)"></div>
              <span @click='delImageIOS(index)' class="remove">x</span>
            </div>
          </li>
          <li class="line" @click="addImage()">
            <div class="input-container"></div>
          </li>
        </ul>
      </div>
      <div class="prompt">
        <span>（拍照上传，不能超过6张图片）</span>
      </div>
      <div class="text_content">
        <textarea @keyup="writeContent" @input="writeContent" name="" id="" placeholder="请简单描述存在的问题" cols="30" rows="10"
                  v-model.trim="resolvent"
                  maxlength="100"></textarea>
        <div class="count">
          {{currentCount}}/{{totalCount-currentCount}}
        </div>
      </div>
    </div>
  </div>
</template>

<script>
  import headTop from '../header/Header.vue'
  import { Toast, Indicator } from 'mint-ui'
  import wx from 'weixin-js-sdk'
  import commonUrl from '../../common/js/commonUrl.js'
  import qs from 'qs'
  import { submitEveryCheck, getCheckEveryPublish, editVeryCheck } from '../../api/jianli.js'

  export default {
    name: 'GoCheckPublish',
    data () {
      return {
        images: {
          localId: [],
          iosLocalId: []
        },
        maxSize: 0,
        ready: false,
        isIOS: false,
        serverId: [],
        totalCount: 100,
        currentCount: 0,
        resolvent: '',
        img: [],
        titleName: ''
      }
    },
    components: {
      headTop
    },
    mounted () {
      // this.titleName = decodeURIComponent(this.$route.params.name)
      // console.log(this.$route.params.name)
    },
    created () {
      if (this.$route.params.hid != 0) {
        this._getCheckEveryPublish()
      }
      // 初始化JSConfig
      const urlLink = `${commonUrl.apihost}index.php/wx/wx_jssdk/getSignPackage`
      var data = {
        url: window.location.href.split('#')[0]
      }
      this.$http.post(urlLink, qs.stringify(data), {headers: {'Content-Type': 'application/x-www-form-urlencoded'}}).then(res => {
        if (res.data.code === 200) {
          wx.config({
            debug: false,
            appId: res.data.data.appId,
            nonceStr: res.data.data.nonceStr,
            rawString: res.data.data.rawString,
            signature: res.data.data.signature,
            timestamp: res.data.data.timestamp,
            jsApiList: ['chooseImage', 'previewImage', 'getLocalImgData', 'uploadImage']
          })
          this.ready = true
        }
      })
    },
    methods: {
      writeContent () {
        this.currentCount = this.resolvent.length
        let remainCount = this.totalCount - this.currentCount
        if (!remainCount) {
          Toast({
            message: '字数不能超过100',
            position: 'middle',
            duration: 1000
          })
        }
      },
      addImage () {
        if (this.ready) {
          var self = this
          var currentSize = this.images.localId.length
          if ((this.serverId.length + this.img.length) >= 6) {
            Toast({
              message: '图片不能超过6张',
              position: 'middle',
              duration: 1000
            })
            return false
          }
          wx.chooseImage({
            count: 6 - this.img.length - currentSize, // 默认9
            sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ['camera', 'album'], // 可以指定来源是相册还是相机，默认二者都有
            success: (res) => {
              self.images.localId = self.images.localId.concat(res.localIds)
              if (window.__wxjs_is_wkwebview) {
                self.isIOS = true

                function readImages () {
                  wx.getLocalImgData({
                    localId: self.images.localId[currentSize],
                    success: function (res) {
                      var localData = res.localData
                      localData = localData.replace('jgp', 'jpeg')
                      self.images.iosLocalId.push(localData)
                      currentSize++
                      if (currentSize < self.images.localId.length) {
                        readImages()
                      }
                    },
                    fail: (res) => {
                      alert(res.errMsg)
                    }
                  })
                }

                readImages()
              }
              self._upload(currentSize)
            },
            fail: (err) => {
              console.log(err)
            }
          })
        }
      },
      _upload (i) {
        wx.uploadImage({
          localId: this.images.localId[i], // 需要上传的图片的本地ID，由chooseImage接口获得
          isShowProgressTips: 1, // 默认为1，显示进度提示
          success: (res) => {
            i++
            this.serverId.push(res.serverId) // 返回图片的服务器端ID
            // this.$emit('getImage', this.serverId)
            if (i < this.images.localId.length) {
              setTimeout(() => {
                this._upload(i)
              }, 100)
            }
          }
        })
      },
      delImage (index) {
        this.images.localId.splice(index, 1)
        this.serverId.splice(index, 1)
      },
      delImageIOS (index) {
        this.images.iosLocalId.splice(index, 1)
        this.images.localId.splice(index, 1)
        this.serverId.splice(index, 1)
      },
      deleteEveryImage (img, index) {
        img.splice(index, 1)
        this.img = img
      },
      preview (index) {
        wx.previewImage({
          current: this.images.localId[index], // 当前显示图片的http链接
          urls: this.images.localId // 需要预览的图片http链接列表
        })
      },
      previewImg (img, index) {
        wx.previewImage({
          current: this.img[index], // 当前显示图片的http链接
          urls: this.img // 需要预览的图片http链接列表
        })
      },
      // 首次提交查验内容
      submitCheck () {
        setTimeout(function () {
          Indicator.close()
        }, 6000)
        if (!this.resolvent || !this.resolvent.trim()) {
          Toast({
            message: '问题描述必填',
            position: 'middle',
            duration: 1000
          })
          return
        }
        Indicator.open({
          spinnerType: 'fading-circle'
        })
        submitEveryCheck(this.$route.params.id, this.$route.params.liftNum, this.resolvent, this.serverId, this.$route.params.relatedId).then(res => {
          if (res.code === 200) {
            Indicator.close()
            Toast({
              message: '提交成功',
              position: 'middle',
              duration: 1000
            })
            this.$router.back()
          } else {
            Toast({
              message: '提交失败',
              position: 'middle',
              duration: 1000
            })
          }
        })
      },
      // 重新提交查验内容
      reSubmitCheck () {
        setTimeout(function () {
          Indicator.close()
        }, 6000)
        if (!this.resolvent || !this.resolvent.trim()) {
          Toast({
            message: '问题描述必填',
            position: 'middle',
            duration: 1000
          })
          return
        }
        Indicator.open({
          spinnerType: 'fading-circle'
        })
        editVeryCheck(this.$route.params.hid, this.resolvent, this.serverId, this.img).then(res => {
          if (res.code === 200) {
            Indicator.close()
            Toast({
              message: '编辑成功',
              position: 'middle',
              duration: 1000
            })
            this.$router.back()
          } else {
            Toast({
              message: '编辑失败，退出重试',
              position: 'middle',
              duration: 1000
            })
          }
        })
      },
      // 获取每一个类别查验的内容
      _getCheckEveryPublish () {
        getCheckEveryPublish(this.$route.params.hid).then(res => {
          if (res.code === 200) {
            this.resolvent = res.data.resolvent
            this.currentCount = this.resolvent.length
            this.img = res.data.img
          }
        })
      }
    }
  }
</script>

<style lang="scss">
  @import '../../common/sass/mixin.scss';

  .go-check-publish {
    .rent_main {
      width: 100%;
      padding-top: 40px;
      background-color: #fff;
      .text_content {
        padding: 10px;
        position: relative;
        .mint-cell:first-child .mint-cell-wrapper {
          background-color: #f2f2f2;
          border-radius: 6px;
          .mint-field-core {
            resize: none;
            background-color: #f2f2f2;
            font-size: 14px;
          }
        }
        textarea {
          box-sizing: border-box;
          width: 100%;
          padding: 10px;
          height: 100px;
          background: #f2f2f2;
          border-radius: 5px;
          resize: none;
          outline: none;
          border: none;
          font-size: 14px;
        }
        .count {
          position: absolute;
          bottom: 20px;
          right: 20px;
          color: #0078de;
        }
      }
      .vue-upload-img-multiple {
        width: 100%;
        height: 100%;
        padding: 10px;
        box-sizing: border-box;
        display: inline-block;
        ul {
          display: flex;
          flex-wrap: wrap;
          li {
            width: 25%;
            margin-top: 5px;
            text-align: center;
            .loading {
              display: block;
              margin: 0 auto;
              margin-top: 20px;
            }
            .img_size {
              display: inline-block;
              position: relative;
              .picture {
                width: 70px;
                height: 70px;
                float: left;
                border-radius: 4px;
                background-position: center center;
                background-repeat: no-repeat;
                background-size: cover;
              }
              .remove {
                position: absolute;
                top: -6px;
                right: -4px;
                width: 18px;
                height: 18px;
                z-index: 11;
                line-height: 18px;
                text-align: center;
                border-radius: 50%;
                // border-bottom: 1px solid #000;
                background-color: red;
                color: #fff;
                font-size: 15px;
              }
            }
          }
          .input-container {
            display: inline-block;
            width: 70px;
            height: 70px;
            background-size: 70px 70px;
            @include bgimg('./images/fabu');
            text-align: center;
          }
          // .file-input {
          //   height: 70px;
          //   width: 70px;
          //   opacity: 0;
          //   font-size: 0;
          // }
        }
      }
      .prompt {
        width: 100%;
        height: 30px;
        text-align: left;
        span {
          font-size: 13px;
          line-height: 30px;
          color: red;
          margin-left: 5px;
        }
      }
    }
  }
</style>
